import React, { Component } from "react";
import { connect } from "dva";
import { routerRedux } from "dva/router";
import { Card, Button, Icon, Input, message, Tag, Form, Upload, Table, Pagination } from "antd";
import { formatMessage } from 'umi-plugin-react/locale';
import MarkdownEditor from "@/utils/vditorContent";
import { docAddAttachDoc, docEditAttachDoc, docUploadAttach, getFileInfo } from "@/services/knowledgeFile";

class AddFile extends Component {
	constructor(props) {
		super(props);
		this.state = {
			isShowTitle: false,
			content: '',
			title: '',
			btnLoading: false,
			fileDocList: [],
		};
		this.columns = [
			{
				title: formatMessage({ id: 'editFile.common.fileName' }),
				dataIndex: 'name',
				key: 'name',
			},
			{
				title: formatMessage({ id: 'editFile.common.size' }),
				dataIndex: 'size',
				key: 'size',
				width: 200,
			},
			{
				title: formatMessage({ id: 'editFile.common.operation' }),
				width: 160,
				render: (text, item) => {
					return (
						<span style={{ color: 'red' }} onClick={() => this.removeFileDoc(item)}>{formatMessage({ id: 'editFile.common.delete' })}</span>
					);
				},
			},
		];
		this.vEditorRef = React.createRef();
	}

	componentDidMount() {
		const { location: { query } } = this.props;
		if (query.id) {
			this.info(query.id);
		};
	}

	info = async id => {
		let that = this;
		let res = await getFileInfo({ id });
		if (res.code === 0) {
			if (this.vEditorRef) {
				that.setState({
					title: res.data.docTitle,
					content: res.data.docContent,
					fileDocList: res.data.relAttachFiles,
				});
				this.vEditorRef.current.setContent(res.data.docContent, () => {
					that.setState({
						title: res.data.docTitle,
						content: res.data.docContent,
						fileDocList: res.data.relAttachFiles,
					})
				});
			} else {
				that.setState({
					title: res.data.docTitle,
					content: res.data.docContent,
					fileDocList: res.data.relAttachFiles,
				})
			};
		}
	}


	setContent = () => {
		let { content } = this.state;
		if (this.vEditorRef) {
			this.vEditorRef.current.setContent(content);
		};
	}

	backRouter = () => {
		this.getKnowledgeFileList();
	}

	setTitle = e => {
		this.setState({ title: e.target.value })
	}

	handleChange = (info) => {
		// if (info.file.status !== 'uploading') {
		//   console.log(info.file, info.fileList);
		// };
		// if (info.file.status === 'done') {
		//   this.$message.success(`${info.file.name} file uploaded successfully`);
		// } else if (info.file.status === 'error') {
		//   this.$message.error(`${info.file.name} file upload failed.`);
		// }
	}

	getFileNameType = fileName => {
		let type = fileName ? fileName.split('.') ? fileName.split('.').length > 1 ? fileName.split('.')[fileName.split('.').length-1] : null : null : null;
		return type;
	}

	beforeUploadFile = (file) => {
		console.log(file);
		if (file.size / 1024 / 1024 > 25) {
			message.error(formatMessage({ id: 'editFile.addFile.maxFileSize' }));
			return false;
		} else if (
			this.getFileNameType(file.name).toLowerCase() !== 'txt' &&
			this.getFileNameType(file.name).toLowerCase() !== 'pdf' &&
			this.getFileNameType(file.name).toLowerCase() !== 'doc' &&
			this.getFileNameType(file.name).toLowerCase() !== 'docx' &&
			this.getFileNameType(file.name).toLowerCase() !== 'xls' &&
			this.getFileNameType(file.name).toLowerCase() !== 'xlsx' &&
			this.getFileNameType(file.name).toLowerCase() !== 'ppt' &&
			this.getFileNameType(file.name).toLowerCase() !== 'pptx' &&
			this.getFileNameType(file.name).toLowerCase() !== 'md'
		) {
			message.error(formatMessage({ id: 'editFile.addFile.fileTypeLimit' }))
			return false;
		} else {
			this.uploadFile(file);
			return false;
		}
	}

	uploadFile = async (file) => {
		let { fileDocList } = this.state;
		let _this = this;
		const formData = new FormData();
		formData.append('files', file);
		let res = await docUploadAttach(formData);
		// console.log('==========>>>>>>>>>>>>>>>>>>>>>>>', res);
		if (res.code === 0) {
			this.setState({ fileDocList: [...res.data, ...fileDocList] })
		};
		// const formData = new FormData();
		// formData.append('userId', commonDataClass.applicationUserInfo.userId);
		// formData.append('files', file);
		// let loginTokenObj = window.localStorage.getItem('loginToken') ? JSON.parse(window.localStorage.getItem('loginToken')) : null;
		// let headers = {
		// 	"Content-Type": 'application/x-www-form-urlencoded',
		// 	"Application-Id": commonDataClass.applicationId,
		// 	"Custom-Auth-Token": loginTokenObj ? `Bearer ${loginTokenObj[commonDataClass.applicationId]}` : undefined,
		// };
		// axios.post($config.robotHost+'/cloud/custom/doc/uploadAttach', formData, { headers }).then(res => {
		// 	console.log(res);
		// 	if (res.data.code == 0) {
		// 		_this.fileDocList = [...res.data.data, ..._this.fileDocList];
		// 	} else {
		// 		_this.$messageBox.Error({ message: res.data.message, duration: 3000 });
		// 	}
		// });
	}

	removeFileDoc = (file) => {
		let { fileDocList } = this.state;
		fileDocList = fileDocList.filter(item => item.id != file.id);
		this.setState({ fileDocList })
	}

	save = () => {
		const { match: { params: { id }, }, route, location: { params, query } } = this.props;
		const { title, content, fileDocList } = this.state;
		if (!title || title == '') {
			return message.error(formatMessage({ id: 'editFile.addFile.fileNameRequired' }))
		};
		if (!content || content === '' || content == '\n') {
			return message.error(formatMessage({ id: 'editFile.addFile.contentRequired' }))
		};
		let relAttachIds = fileDocList.map(item => item.id);
		let obj = {
			libraryId: id,
			categoryId: query.fileCategoryId,
			categoryPath: query.fileCategoryPath,
			docTitle: title,
			docContent: content,
			relAttachIds,
		};
		this.setState({ btnLoading: true }, async () => {
			if (query.id) {
				obj.id = query.id;
				let res = await docEditAttachDoc(obj);
				// console.log(res);
				if (res.code == 0) {
					message.info(res.msg);
					this.setState({ btnLoading: false });
				} else {
					this.setState({ btnLoading: false });
				}
			} else {
				let res = await docAddAttachDoc(obj);
				// console.log(res);
				if (res.code == 0) {
					message.info(res.msg);
					this.getKnowledgeFileList();
					this.setState({ btnLoading: false });
				} else {
					this.setState({ btnLoading: false });
				}
			}
		})
	}

	// 新增自定义文档
	getKnowledgeFileList = () => {
		const { match: { params: { id }, }, location: { query,pathname }, dispatch } = this.props;
		let url = pathname.indexOf("publicResource") ? "/publicResource/documentLibrary/" + id + "/file" : "/documentLibrary/" + id + "/file";
		dispatch(routerRedux.push({ pathname:url, query: { fileCategoryId: query.fileCategoryId } }));
	}

	render() {
		const { match: { params: { id }, }, route, location: { params, query } } = this.props;
		const { isShowTitle, title, btnLoading, content, fileDocList } = this.state;
		const optionDisabled = query.optionDisabled == 'true' || query.optionDisabled == true ? true : false; 

		return (
			<Card bordered={false}>
				<Form layout="vertical">
					<Form.Item label={formatMessage({ id: 'editFile.addFile.attachmentName' })}>
						<Input placeholder={formatMessage({ id: 'editFile.addFile.fileNamePlaceholder' })} value={title} onChange={e => this.setTitle(e)} />
					</Form.Item>
					<Form.Item label={formatMessage({ id: 'editFile.addFile.attachmentDescription' })}>
						<MarkdownEditor
							value={content}
							name='markdown-editor'
							id='markdown-editor'
							height='240px'
							width='700'
							onChange={value => this.setState({ content: value })}
							setContent={this.setContent}
							ref={this.vEditorRef}
						/>
					</Form.Item>
					<Form.Item>
						<Upload
							name='file'
							listType='picture'
							showUploadList={false}
							beforeUpload={this.beforeUploadFile}
							onChange={this.handleChange}
							accept=".txt,.pdf,.doc,.docx,.xls,.xlsx,.ppt,.pptx,.md"
						>
							<Button> <Icon type="upload" /> {formatMessage({ id: 'editFile.addFile.addAttachment' })} </Button>
						</Upload>
					</Form.Item>
					<Form.Item>
						<Table
							dataSource={fileDocList}
							columns={this.columns}
							rowKey="id"
						/>
					</Form.Item>
					<Form.Item>
						<Button type="primary" style={{ marginRight: 10 }} onClick={this.save} loading={btnLoading} disabled={optionDisabled}>{formatMessage({ id: 'editFile.addFile.submit' })}</Button>
						<Button onClick={this.backRouter}>{formatMessage({ id: 'editFile.addFile.cancel' })}</Button>
					</Form.Item>
				</Form>
			</Card>
		);
	}
}

export default connect(({ user }) => ({
	currentUser: user.currentUser,
}))(Form.create()(AddFile));